package com.mao.server.aop;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ArrayUtil;
import com.mao.server.annotation.HoneyLogs;
import com.mao.server.domain.po.Logs;
import com.mao.server.domain.po.User;
import com.mao.server.service.LogsService;
import com.mao.server.service.UserService;
import com.mao.server.utils.BaseContext;
import com.mao.server.utils.IpUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
@Aspect
@Slf4j
public class LogsAspect {
    @Resource
    LogsService logsService;

    @Resource
    UserService userService;

    @AfterReturning(pointcut = "@annotation(honeyLogs)", returning = "jsonResult")
    public void recordLog(JoinPoint joinPoint, HoneyLogs honeyLogs, Object jsonResult) {
        User currentUser = userService.getById(BaseContext.getCurrentId());
        // 用户未登录的情况下  currentUser是 null  是 null 的话我们就要从参数里面获取操作人信息
        if (currentUser == null) {
            // 登录、注册
            Object[] args = joinPoint.getArgs();
            if (ArrayUtil.isNotEmpty(args)) {
                if (args[0] instanceof User) {
                    currentUser = (User) args[0];
                }
            }
        }
                if (currentUser == null) {
            log.error("记录日志信息报错，未获取到当前操作用户信息");
            return;
        }
        // 获取HttpServletRequest对象
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        // 获取IP信息
        String ipAddr = IpUtils.getIpAddr(request);
        //组装日志的实体对象
        Logs logs = Logs.builder()
                .user(currentUser.getUsername())
                .operation(honeyLogs.operation())
                .type(honeyLogs.type().getValue())
                .ip(ipAddr)
                .time(DateUtil.now())
                .build();

        // 插入数据到数据库
        ThreadUtil.execAsync(() -> {
            logsService.save(logs);
        });
    }
}
